package com.example.web.system.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.date.DateTime;
import com.example.utils.RedisConstant;
import com.example.utils.Result;
import com.example.web.system.entity.LoginParam;
import com.example.web.system.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
@Api(tags = "登录处理类")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/captcha")
    @ApiOperation("验证码处理")
    public Result captcha(){
        //获取验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 40, 4, 11);
        //获得验证码压缩图片
        String imageBase64 = lineCaptcha.getImageBase64Data();//这个方法自动拼好了前缀
        //前端如何翻译压缩后的验证码图片： <img src="data:image/png;,ivB0......"/>
//        imageBase64="data:image/png;base64,"+imageBase64;
        //获得验证码内容
        String code = lineCaptcha.getCode();
        //获得验证码id
        String captchaId=UUID.randomUUID().toString();

        //存验证码到redis
        redisTemplate.opsForValue().set(
                RedisConstant.CAPTCHA_PRE+captchaId,code, RedisConstant.CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS
        );

        //响应数据
        Map<String, Object> map = new HashMap<>();
        map.put("captchaId",captchaId);
        map.put("imageBase64",imageBase64);
        return Result.success(map);
    }

    @Autowired
    private LoginService loginService;
    @PostMapping("/login")
    @ApiOperation("登录处理")
    public Result login(@RequestBody
                            @Valid
                            @ApiParam (value = "登录需要参数",required = true)
                        LoginParam loginParam){
        return loginService.login(loginParam);
    }

    @PostMapping("/logout")
    @ApiOperation("安全退出")
    public Result logout(){
        return  loginService.logout();
    }

    @GetMapping("/getInfo")
    @ApiOperation("获取当前用户信息")
    public Result getInfo(){

        return  loginService.getInfo();
    }


    @GetMapping("/time")
    @ApiOperation("系统时间测试")
    public Result time(){
        return Result.success(new DateTime());
    }

}
